package com.oocl.chat.webcontroller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {
	private ServerSocket serverSocket;
	private Socket socket;
	private OutputStream out;
	private InputStream in;
	private Sender sender;

	public HttpServer(int port) throws IOException {

		serverSocket = new ServerSocket(port);
		System.out.println("Web Server open");
		sender = new Sender();
	}

	public void start() {

		while (true) {
			try {
				socket = serverSocket.accept();
				in = socket.getInputStream();
				out = socket.getOutputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in));
				String line = reader.readLine();
				if (line == null) {
					continue;
				}
				line=line.split(" ")[1];
				System.out.println(line);
				out.write("HTTP/1.1 200 OK\r\n\r\n".getBytes());
				sender.send(line,out);
				closeSocket();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	void closeSocket() {
		try {
			socket.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		System.out.println("...end");
	}
}
